package com.websockettest.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.Session;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebSocketSessionUtils {
	public static Map<String, Session> client = new HashMap<>();
	public static Object obj = new Object();
	/**
	 * 添加连接
	 * @param userId
	 * @param session
	 */
	public static void addSession(String userId, Session session){
		synchronized (obj) {
			try{
				removeSession(userId);
                client.put(userId, session);
            }catch(Exception e){
				log.error(e.getMessage(), e);
			}
		}
	}
	/**
	 * 移除连接
	 * @param userId
     */
	public static void removeSession(String userId){
		synchronized (obj) {
			try{
                Session session = getSessions(userId);
				if(session != null){
                    session.close();//断开连接
				}
			}catch(Exception e){
                log.error(e.getMessage(), e);
			}
		}
	}
	
	/**
	 * 获取连接
	 * @param userId
	 * @return
	 */
	public static Session getSessions(String userId){
	    if (!client.containsKey(userId)) {
	        return null;
        }
        return client.get(userId);
	}

	// 推送消息
	public static void sendMessage(String userId, String message) {
		Session session = getSessions(userId);
		if (session != null) {
			try {
				session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				log.error("消息推送失败，", e);
			}
		}
	}
}
